#!/usr/bin/env python3
"""调试对话查找问题"""

import asyncio
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from src.config import load_config
from src.database.chromadb_client import ChromaDBClient
from src.database.mongodb_client import MongoDBClient
from src.core.conversation_manager import ConversationManager
from src.database.manager import DatabaseManager

async def debug_conversation_lookup():
    """调试对话查找问题"""
    print("=== 调试对话查找问题 ===")
    
    try:
        # 加载配置
        config = load_config()
        
        # 初始化 ChromaDBClient
        chromadb_client = ChromaDBClient(config)
        await chromadb_client.connect()
        
        print("✅ ChromaDBClient 连接成功")
        
        # 搜索获取对话ID
        query = "王者荣耀"
        user_id = "default_user"
        limit = 5
        
        print(f"\n1. 从 ChromaDB 搜索获取对话ID...")
        vector_results = await chromadb_client.search_conversations(query, user_id, limit)
        
        print(f"   搜索结果数量: {len(vector_results)}")
        
        # 提取对话ID
        conversation_ids = set()
        for result in vector_results:
            conv_id = result.get('conversation_id')
            if conv_id:
                conversation_ids.add(conv_id)
                print(f"   找到对话ID: {conv_id}")
        
        print(f"   唯一对话ID数量: {len(conversation_ids)}")
        
        # 初始化 MongoDB 客户端
        print(f"\n2. 检查 MongoDB 中的对话记录...")
        mongodb_client = MongoDBClient(config)
        await mongodb_client.connect()
        
        print("✅ MongoDB 连接成功")
        
        # 检查每个对话ID
        for conv_id in conversation_ids:
            print(f"\n   检查对话ID: {conv_id}")
            
            # 使用 MongoDB 客户端直接查找
            conv_info = await mongodb_client.get_conversation(conv_id)
            
            if conv_info:
                print(f"     ✅ 在 MongoDB 中找到对话")
                print(f"     标题: {conv_info.get('title', 'N/A')}")
                print(f"     用户ID: {conv_info.get('user_id', 'N/A')}")
                print(f"     状态: {conv_info.get('status', 'N/A')}")
                print(f"     创建时间: {conv_info.get('created_at', 'N/A')}")
            else:
                print(f"     ❌ 在 MongoDB 中未找到对话")
                
                # 检查是否有类似的记录
                print(f"     检查 MongoDB conversations 集合...")
                collection = mongodb_client.get_collection('conversations')
                
                # 查找所有记录
                all_conversations = await collection.find({}).to_list(length=None)
                print(f"     MongoDB 中总对话数: {len(all_conversations)}")
                
                if all_conversations:
                    print(f"     示例对话记录:")
                    for i, conv in enumerate(all_conversations[:3]):
                        print(f"       [{i+1}] _id: {conv.get('_id')}")
                        print(f"           conversation_id: {conv.get('conversation_id')}")
                        print(f"           title: {conv.get('title')}")
                        print(f"           user_id: {conv.get('user_id')}")
        
        # 测试 ConversationManager
        print(f"\n3. 测试 ConversationManager...")
        
        # 初始化数据库管理器
        db_manager = DatabaseManager(config)
        await db_manager.initialize()
        
        # 初始化对话管理器
        conversation_manager = ConversationManager(db_manager, config)
        await conversation_manager.initialize()
        
        print("✅ ConversationManager 初始化成功")
        
        # 测试搜索
        search_results = await conversation_manager.search_conversations(query, user_id, limit)
        
        print(f"   ConversationManager 搜索结果数量: {len(search_results)}")
        
        if search_results:
            for i, result in enumerate(search_results):
                print(f"     [{i+1}] 对话ID: {result.get('conversation_id')}")
                print(f"         标题: {result.get('title')}")
                print(f"         相似度: {result.get('similarity')}")
        else:
            print(f"     ❌ ConversationManager 搜索无结果")
        
        # 清理
        await conversation_manager.cleanup()
        await db_manager.cleanup()
        
        print("\n✅ 调试完成")
        
    except Exception as e:
        print(f"❌ 调试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(debug_conversation_lookup())